package cn.ysl.management.service.impl;

import cn.ysl.management.model.Admin;
import cn.ysl.management.repository.AdminMapper;
import cn.ysl.management.service.AdminService;
import cn.ysl.management.service.exception.AdminDuplicatedException;
import cn.ysl.management.service.exception.AdminNotFoundException;
import cn.ysl.management.service.exception.InsertException;
import cn.ysl.management.service.exception.PasswordNotMatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Locale;
import java.util.UUID;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;

    public void reg(Admin admin) {
        String adminName = admin.getAdminName();
        Admin result = adminMapper.getAdminByName(adminName);
        if (result != null) {
            throw new AdminDuplicatedException("当前管理员名已被占用");
        }

        String oldPassword = admin.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        admin.setSalt(salt);
        String newPassword = getMD5Password(oldPassword, salt);
        admin.setPassword(newPassword);

        admin.setIsDelete(0);

        admin.setCreatedUser(adminName);
        admin.setModifiedUser(adminName);

        Date date = new Date();
        admin.setCreatedTime(date);
        admin.setModifiedTime(date);

        Integer rows = adminMapper.insert(admin);
        if (rows != 1) {
            throw new InsertException("在注册过程中产生了未知异常");
        }
    }

    public Admin login(String adminName, String password) {
        Admin result = adminMapper.getAdminByName(adminName);
        if (result == null) {
            throw new AdminNotFoundException("未找到相应的管理员信息");
        }

        String salt = result.getSalt();
        String MD5Password = getMD5Password(password, salt);

        if (!result.getPassword().equals(MD5Password)) {
            throw new PasswordNotMatchException("账户名密码不匹配");
        }

        if (result.getIsDelete() == 1) {
            throw new AdminDuplicatedException("此账户当前处于不可用状态");
        }

        Admin out = new Admin();
        out.setAid(result.getAid());
        out.setAdminName(adminName);
        out.setAvatar(result.getAvatar());

        return out;
    }

    /** 定义一个md5算法的加密处理 */
    private String getMD5Password(String oldPassword, String salt) {

        for (int i = 0; i < 3; ++i) {
            // md5加密算法方法的调用
            oldPassword = DigestUtils.md5DigestAsHex((salt + oldPassword + salt).getBytes()).toUpperCase();
        }
        return oldPassword;
    }

}
